import React, { useState, useEffect } from 'react';
import { Modal, Input, Button, List, Tree, Radio, Space, Checkbox } from 'antd';
import { SearchOutlined, CloseOutlined, CaretDownOutlined, CaretRightOutlined } from '@ant-design/icons';
import type { DataNode } from 'antd/es/tree';
import type { RadioChangeEvent } from 'antd';
import './UserSelectModal.css';

interface User {
  id: string;
  name: string;
  children?: User[];
}

interface UserWithPermission extends User {
  permission?: string;
  allowedKnowledgeBases?: string[]; // 允许访问的知识库ID列表
}

interface KnowledgeBase {
  id: string;
  name: string;
  children?: KnowledgeBase[];
}

interface UserSelectModalProps {
  visible: boolean;
  onCancel: () => void;
  onConfirm: (selectedUsers: UserWithPermission[]) => void;
}

const UserSelectModal: React.FC<UserSelectModalProps> = ({
  visible,
  onCancel,
  onConfirm
}) => {
  // 模拟用户数据
  const allUsers: User[] = [
    { id: '1', name: '教工组', children: [{ id: '11', name: '教工1' }, { id: '12', name: '教工2' }] },
    { id: '2', name: '学生组', children: [{ id: '21', name: '学生1' }, { id: '22', name: '学生2' }] },
    { id: '3', name: '领导组', children: [{ id: '31', name: '领导1' }, { id: '32', name: '领导2' }] },
  ];

  // 模拟知识库数据
  const allKnowledgeBases: KnowledgeBase[] = [
    { id: 'kb1', name: '政策文件' },
    { id: 'kb2', name: '学院文件' }
  ];

  // 当前步骤：1-选择用户，2-权限设置
  const [currentStep, setCurrentStep] = useState<1 | 2>(1);
  // 选中的用户ID数组
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  // 展开的节点ID数组
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [searchValue, setSearchValue] = useState('');
  // 用户权限映射表，记录每个用户的权限设置
  const [userPermissions, setUserPermissions] = useState<Record<string, string>>({});
  // 用户可访问知识库映射表
  const [userKnowledgeBases, setUserKnowledgeBases] = useState<Record<string, string[]>>({});

  // 知识库选择模态框
  const [kbSelectVisible, setKbSelectVisible] = useState(false);
  // 当前正在编辑权限的用户ID
  const [currentEditingUserId, setCurrentEditingUserId] = useState<string>('');
  // 知识库选择的搜索值
  const [kbSearchValue, setKbSearchValue] = useState('');
  // 当前选中的知识库ID
  const [selectedKbIds, setSelectedKbIds] = useState<string[]>([]);

  // 保存过滤后可见的节点key
  const [visibleKeys, setVisibleKeys] = useState<Set<React.Key>>(new Set());

  // 获取某个节点下所有子节点的key
  const getAllChildrenKeys = (id: React.Key, users: User[]): React.Key[] => {
    const result: React.Key[] = [];

    const findAndCollectKeys = (nodeId: React.Key, userList: User[]) => {
      for (const user of userList) {
        if (user.id === nodeId) {
          if (user.children && user.children.length > 0) {
            user.children.forEach(child => {
              result.push(child.id);
              if (child.children && child.children.length > 0) {
                findAndCollectKeys(child.id, [child]);
              }
            });
          }
          return;
        }

        if (user.children && user.children.length > 0) {
          findAndCollectKeys(nodeId, user.children);
        }
      }
    };

    findAndCollectKeys(id, users);
    return result;
  };

  // 将用户数据转换为树节点格式
  const convertToTreeData = (users: User[]): DataNode[] => {
    return users.map(user => ({
      key: user.id,
      title: user.name,
      children: user.children ? convertToTreeData(user.children) : undefined
    }));
  };

  // 将展平的用户ID列表转换回用户对象
  const getUsersFromKeys = (keys: React.Key[]): UserWithPermission[] => {
    const result: UserWithPermission[] = [];

    const findUserById = (id: React.Key, users: User[]): User | undefined => {
      for (const user of users) {
        if (user.id === id) {
          // 为用户对象添加完整路径信息以便显示
          const userClone = { ...user };
          // 移除children防止右侧列表显示过于复杂
          delete userClone.children;
          return userClone;
        }
        if (user.children) {
          const found = findUserById(id, user.children);
          if (found) return found;
        }
      }
      return undefined;
    };

    keys.forEach(key => {
      const user = findUserById(key, allUsers);
      if (user) {
        const userWithPerm: UserWithPermission = {
          ...user,
          permission: userPermissions[String(key)] || 'full', // 默认为'full'
          allowedKnowledgeBases: userKnowledgeBases[String(key)] || [] // 默认为空数组
        };
        result.push(userWithPerm);
      }
    });

    return result;
  };

  // 获取所有用户ID（扁平化）
  const getAllUserIds = (users: User[]): string[] => {
    const result: string[] = [];
    const traverse = (user: User) => {
      result.push(user.id);
      if (user.children) {
        user.children.forEach(traverse);
      }
    };
    users.forEach(traverse);
    return result;
  };

  // 计算所有用户总数
  const getTotalUserCount = (): number => {
    return getAllUserIds(allUsers).length;
  };

  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value.trim();
    setSearchValue(value);

    if (value) {
      // 搜索时展开所有匹配的节点
      const matchedKeys: React.Key[] = [];
      const searchNodes = (nodes: User[]) => {
        nodes.forEach(node => {
          if (node.name.toLowerCase().includes(value.toLowerCase())) {
            matchedKeys.push(node.id);
          }
          if (node.children) {
            searchNodes(node.children);
          }
        });
      };
      searchNodes(allUsers);
      setExpandedKeys(matchedKeys);
    } else {
      // 清空搜索时折叠所有节点
      setExpandedKeys([]);
    }
  };

  const handleSelect = (checkedKeys: React.Key[] | { checked: React.Key[]; halfChecked: React.Key[] }) => {
    // 当返回的checkedKeys是一个对象时，提取checked数组
    const keys = Array.isArray(checkedKeys) ? checkedKeys : checkedKeys.checked;

    // 处理子节点全选逻辑，但只处理可见的节点
    let allSelectedKeys = [...selectedKeys]; // 保留已选的节点

    // 移除被取消选中的节点
    allSelectedKeys = allSelectedKeys.filter(key =>
      keys.includes(key) || !visibleKeys.has(key)
    );

    // 添加新选中的节点
    keys.forEach(key => {
      if (!allSelectedKeys.includes(key)) {
        allSelectedKeys.push(key);
      }

      // 只有当节点在可见范围内时，才获取其子节点
      if (visibleKeys.has(key)) {
        const childrenKeys = getAllChildrenKeys(key, allUsers);
        // 只添加可见的子节点
        const visibleChildrenKeys = childrenKeys.filter(childKey => visibleKeys.has(childKey));

        // 合并子节点，避免重复
        visibleChildrenKeys.forEach(childKey => {
          if (!allSelectedKeys.includes(childKey)) {
            allSelectedKeys.push(childKey);
          }
        });
      }
    });

    setSelectedKeys(allSelectedKeys);

    // 为新选择的用户初始化权限设置为'full'
    const newUserPermissions = { ...userPermissions };
    allSelectedKeys.forEach(key => {
      if (!userPermissions[String(key)]) {
        newUserPermissions[String(key)] = 'full';
      }
    });
    setUserPermissions(newUserPermissions);
  };

  const handleExpand = (newExpandedKeys: React.Key[]) => {
    setExpandedKeys(newExpandedKeys);
  };

  const handleRemoveUser = (key: React.Key) => {
    setSelectedKeys(prev => prev.filter(k => k !== key));

    // 从权限映射表中移除该用户
    const newUserPermissions = { ...userPermissions };
    delete newUserPermissions[String(key)];
    setUserPermissions(newUserPermissions);

    // 从知识库映射表中移除该用户
    const newUserKnowledgeBases = { ...userKnowledgeBases };
    delete newUserKnowledgeBases[String(key)];
    setUserKnowledgeBases(newUserKnowledgeBases);
  };

  // 处理单个用户的权限选择变化
  const handleUserPermissionChange = (userId: string, permission: string) => {
    setUserPermissions(prev => ({
      ...prev,
      [userId]: permission
    }));

    // 如果选择了"所有知识库可问答"，清空该用户的知识库选择
    if (permission === 'full') {
      setUserKnowledgeBases(prev => {
        const newState = { ...prev };
        delete newState[userId];
        return newState;
      });
    }
  };

  // 打开知识库选择模态框
  const handleEditKnowledgeBases = (userId: string) => {
    setCurrentEditingUserId(userId);
    // 设置当前选中的知识库
    setSelectedKbIds(userKnowledgeBases[userId] || []);
    setKbSelectVisible(true);
  };

  // 处理知识库搜索
  const handleKbSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setKbSearchValue(e.target.value.trim());
  };

  // 处理知识库选择变化
  const handleKbSelectChange = (kbId: string, checked: boolean) => {
    if (checked) {
      setSelectedKbIds(prev => [...prev, kbId]);
    } else {
      setSelectedKbIds(prev => prev.filter(id => id !== kbId));
    }
  };

  // 确认知识库选择
  const handleKbSelectConfirm = () => {
    setUserKnowledgeBases(prev => ({
      ...prev,
      [currentEditingUserId]: selectedKbIds
    }));
    setKbSelectVisible(false);
  };

  // 取消知识库选择
  const handleKbSelectCancel = () => {
    setKbSelectVisible(false);
  };

  // 点击下一步，进入权限设置
  const handleNextStep = () => {
    setCurrentStep(2);
  };

  // 点击上一步，返回用户选择
  const handlePrevStep = () => {
    setCurrentStep(1);
  };

  // 完成设置，确认提交
  const handleFinish = () => {
    const selectedUsers = getUsersFromKeys(selectedKeys);
    onConfirm(selectedUsers);
  };

  // 取消操作，重置状态
  const handleCancel = () => {
    setCurrentStep(1);
    onCancel();
  };

  // 过滤树数据
  const filterTreeData = (data: DataNode[]): DataNode[] => {
    if (!searchValue) return data;

    // 保存匹配的节点key，用于后续选择
    const matchedNodeKeys: Set<React.Key> = new Set();

    const filterNodes = (nodes: DataNode[]): DataNode[] => {
      const result: DataNode[] = [];

      for (const node of nodes) {
        const nodeTitle = typeof node.title === 'string' ? node.title : '';
        const matchesSearch = nodeTitle.toLowerCase().includes(searchValue.toLowerCase());

        let filteredChildren: DataNode[] | undefined = undefined;
        if (node.children) {
          filteredChildren = filterNodes(node.children);
        }

        if (matchesSearch || (filteredChildren && filteredChildren.length > 0)) {
          // 将匹配的节点key加入到集合中
          matchedNodeKeys.add(node.key);
          // 如果子节点有匹配的，也加入它们的key
          if (filteredChildren && filteredChildren.length > 0) {
            filteredChildren.forEach(child => {
              matchedNodeKeys.add(child.key);
            });
          }

          result.push({
            ...node,
            children: filteredChildren,
          });
        }
      }

      return result;
    };

    const filteredResult = filterNodes(data);

    // 将匹配的节点key保存为组件的状态
    return filteredResult;
  };

  // 树的渲染配置
  const treeData = filterTreeData(convertToTreeData(allUsers));

  // 提取所有可见节点的key
  // useEffect(() => {
  //   if (!searchValue) {
  //     // 如果没有搜索条件，所有节点都是可见的
  //     setVisibleKeys(new Set(getAllUserIds(allUsers)));
  //   } else {
  //     const visibleNodeKeys = new Set<React.Key>();

  //     const extractKeys = (nodes: DataNode[]) => {
  //       nodes.forEach(node => {
  //         visibleNodeKeys.add(node.key);
  //         if (node.children) {
  //           extractKeys(node.children);
  //         }
  //       });
  //     };

  //     extractKeys(treeData);
  //     setVisibleKeys(visibleNodeKeys);
  //   }
  // }, [searchValue, treeData]);

  // 获取已选择的用户对象列表
  const selectedUsers = getUsersFromKeys(selectedKeys);

  // 过滤知识库列表
  const filteredKnowledgeBases = kbSearchValue
    ? allKnowledgeBases.filter(kb => kb.name.toLowerCase().includes(kbSearchValue.toLowerCase()))
    : allKnowledgeBases;

  return (
    <>
      <Modal
        title={currentStep === 1 ? "选择可见用户" : "问答权限设置"}
        open={visible}
        footer={null}
        onCancel={handleCancel}
        width={640}
        styles={{ body: { padding: '5px' } }}
        maskClosable={false}
        centered
      >
        {currentStep === 1 ? (
          // 第一步：用户选择
          <div className="flex h-[300px] border border-[#C9CEE2] rounded-lg p-4">
            {/* 左侧搜索与用户列表 */}
            <div className="w-1/2 border-r border-[#C9CEE2] pr-4">
              <Input
                placeholder="搜索用户名，部门，或用户"
                prefix={<SearchOutlined style={{ color: '#C0C6CC' }} />}
                className="mb-4"
                value={searchValue}
                onChange={handleSearchChange}
              />
              <div className="overflow-auto h-[220px]">
                <Tree
                  checkable
                  checkedKeys={selectedKeys}
                  expandedKeys={expandedKeys}
                  onCheck={handleSelect}
                  onExpand={handleExpand}
                  treeData={treeData}
                  switcherIcon={({ expanded }) => expanded ?
                    <CaretDownOutlined className="text-[#C0C6CC]" /> :
                    <CaretRightOutlined className="text-[#C0C6CC]" />}
                  blockNode
                />
              </div>
            </div>

            {/* 右侧已选用户 */}
            <div className="w-1/2 pl-4">
              <div className="mb-4 text-[#86909C]">已选: {selectedUsers.length} 个</div>
              <div className="overflow-auto h-[240px]">
                <List
                  dataSource={selectedUsers}
                  renderItem={user => (
                    <List.Item className="p-2 hover:bg-[#F5F7FA]">
                      <div className="flex justify-between w-full items-center">
                        <span>{user.name}</span>
                        <CloseOutlined
                          className="text-[#C0C6CC] cursor-pointer"
                          onClick={() => handleRemoveUser(user.id)}
                        />
                      </div>
                    </List.Item>
                  )}
                />
              </div>
            </div>
          </div>
        ) : (
          // 第二步：权限设置
          <div className="h-[300px] border border-[#C9CEE2] rounded-lg p-6">

            {/* 表格头部 */}
            <div className="flex w-full border-b border-[#E5E6EB]">
              <div className="w-1/3 text-[#1D2129] font-medium">用户组</div>
              <div className="w-2/3 text-[#1D2129] font-medium">权限</div>
            </div>

            {/* 表格内容 - 可滚动区域 */}
            <div className="overflow-auto max-h-[200px]">
              {selectedUsers.map((user, index) => (
                <div key={user.id} className={`flex w-full py-3 ${index !== selectedUsers.length - 1 ? 'border-b border-[#E5E6EB]' : ''}`}>
                  <div className="w-1/3 text-[#4E5969] flex items-center">{user.name}</div>
                  <div className="w-2/3 flex items-center">
                    <Radio.Group
                      onChange={(e) => handleUserPermissionChange(String(user.id), e.target.value)}
                      value={userPermissions[String(user.id)] || 'full'}
                      className="flex items-center"
                    >
                      <Radio value="full" className="mr-4">
                        <span className="text-[#4E5969]">所有知识库可问答</span>
                      </Radio>
                      <Radio value="partial">
                        <span className="text-[#4E5969]">部分知识库可问答</span>
                        {userPermissions[String(user.id)] === 'partial' && (
                          <span
                            className="text-[#7B67EE] ml-1 text-xs cursor-pointer"
                            onClick={() => handleEditKnowledgeBases(String(user.id))}
                          >
                            编辑
                          </span>
                        )}
                      </Radio>
                    </Radio.Group>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* 底部按钮 */}
        <div className="flex justify-end mt-4">
          {currentStep === 1 ? (
            // 第一步底部按钮
            <>
              <Button
                className="mr-2 bg-[#F7F8FA] border-[#E5E6EB] text-[#4E5969]"
                onClick={handleCancel}
              >
                取消
              </Button>
              <Button
                type="primary"
                className="bg-[#6857D6]"
                onClick={handleNextStep}
                disabled={selectedUsers.length === 0}
              >
                下一步{selectedUsers.length > 0 ? ` (${selectedUsers.length})` : ''}
              </Button>
            </>
          ) : (
            // 第二步底部按钮
            <>
              <Button
                className="mr-2 bg-[#F7F8FA] border-[#E5E6EB] text-[#4E5969]"
                onClick={handlePrevStep}
              >
                上一步
              </Button>
              <Button
                type="primary"
                className="bg-[#6857D6]"
                onClick={handleFinish}
              >
                完成
              </Button>
            </>
          )}
        </div>
      </Modal>

      {/* 知识库选择模态框 */}
      <Modal
        title={`选择${selectedKbIds.length}个可回答的知识库`}
        open={kbSelectVisible}
        footer={null}
        onCancel={handleKbSelectCancel}
        width={600}
        maskClosable={false}
        centered
      >
        <div className="flex h-[300px] border border-[#C9CEE2] rounded-lg">
          {/* 左侧知识库选择 */}
          <div className="w-1/2 border-r border-[#C9CEE2] p-4">
            <Input
              placeholder="搜索知识库，部门，或用户"
              prefix={<SearchOutlined style={{ color: '#C0C6CC' }} />}
              className="mb-4"
              value={kbSearchValue}
              onChange={handleKbSearchChange}
            />
            <div className="overflow-auto h-[220px]">
              {filteredKnowledgeBases.map(kb => (
                <div key={kb.id} className="mb-2">
                  <Checkbox
                    checked={selectedKbIds.includes(kb.id)}
                    onChange={(e) => handleKbSelectChange(kb.id, e.target.checked)}
                  >
                    <span className="text-[#4E5969]">{kb.name}</span>
                  </Checkbox>
                </div>
              ))}
            </div>
          </div>

          {/* 右侧已选知识库 */}
          <div className="w-1/2 p-4">
            <div className="mb-4 text-[#86909C]">已选: {selectedKbIds.length} 个</div>
            <div className="overflow-auto h-[220px]">
              {selectedKbIds.map(kbId => {
                const kb = allKnowledgeBases.find(k => k.id === kbId);
                return kb ? (
                  <div key={kb.id} className="flex justify-between items-center p-2 hover:bg-[#F5F7FA]">
                    <span>{kb.name}</span>
                    <CloseOutlined
                      className="text-[#C0C6CC] cursor-pointer"
                      onClick={() => handleKbSelectChange(kb.id, false)}
                    />
                  </div>
                ) : null;
              })}
            </div>
          </div>
        </div>

        {/* 底部按钮 */}
        <div className="flex justify-end mt-4">
          <Button
            className="mr-2 bg-[#F7F8FA] border-[#E5E6EB] text-[#4E5969]"
            onClick={handleKbSelectCancel}
          >
            取消
          </Button>
          <Button
            type="primary"
            className="bg-[#6857D6]"
            onClick={handleKbSelectConfirm}
          >
            确定
          </Button>
        </div>
      </Modal>
    </>
  );
};

export default UserSelectModal; 